import React from 'react';
import {Form, Row, Col, Select, DatePicker, Button} from 'antd';
import {injectIntl} from 'react-intl';
import Grid from '../../components/table/grid';
import DepartmentPicker from '../../components/pickCity/departmentPicker';
import {getYear} from '../../utils/Array';
import moment from 'moment';
import tranStartType from "../../utils/tranStartType";
import axios from "axios/index";
import qs from 'qs'
import {sessionManager} from "../../utils/sessionStorage";

const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;
const {MonthPicker, RangePicker} = DatePicker;


class DepChargeReport extends React.Component {
    constructor(props) {
        super(props);
        this.common = this.props.intl.messages.common;
        this.state = {
            params: {
                dateType: '1',
                date: moment().format('YYYY')
            },
            visible: false,
        };
        this.columns = [
            {
                title: this.common.unit,
                dataIndex: 'orgName',
                key: 'orgName',
            },
            {
                title: this.common.project,
                children: [
                    {
                        title: '充电量（kW）',
                        dataIndex: 'elecSum',
                        key: 'elecSum',
                        align: 'center'
                    },
                    {
                        title: '充电数（次）',
                        dataIndex: 'chargeCnt',
                        key: 'chargeCnt',
                        align: 'center'
                    },
                    {
                        title: '充电时长（分钟）',
                        dataIndex: 'chargeTimeSum',
                        key: 'chargeTimeSum',
                        align: 'center'
                    },
                    {
                        title: '电费（元）',
                        dataIndex: 'elecFeeSum',
                        key: 'elecFeeSum',
                        align: 'center'
                    },
                    {
                        title: '服务费（元）',
                        dataIndex: 'serviceFeeSum',
                        key: 'serviceFeeSum',
                        align: 'center'
                    },
                    {
                        title: this.common.operation,
                        key: 'action',
                        align: 'center',
                        render: (text, record) => (
                            text.orgId!=0&&<a onClick={() => this.modifyCar(text, record)}>查看</a>
                        )
                    }
                ]
            }]
    }

    componentWillMount() {
        this.setState({
            modalParams: this.state.params
        })
    }



    modifyCar = (text) => {
        console.log(text)
        this.setState({
            modalParams: Object.assign(this.state.modalParams, {orgId: text.orgId,isDirect:text.isDirect})
        }, () => {
            this.props.openNewPane(this.state.modalParams)
        });
    };

    onCancel = () => {
        this.setState({
            visible: false
        })
    };

    handleChange = (value) => {
        console.log(`selected ${value}`);
        this.setState({
            params: Object.assign(this.state.params, {dateType: value})
        })
    };

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!!err) {
                return;
            }
            for (let key in values) {
                console.log(key);
                if (key === 'year') {
                    values.date = values[key];
                }
                if (key === 'month') {
                    values.date = values[key].format('YYYY-MM');
                    delete values[key];
                }
                if (key === 'day') {
                    values.date = values[key].format('YYYY-MM-DD')
                    delete values[key];
                }
                if (key === 'selfDefining') {
                    values.startDate = values[key][0].format('YYYY-MM-DD HH:mm:ss');
                    values.endDate = values[key][1].format('YYYY-MM-DD HH:mm:ss');
                    delete values[key];
                }
            }
            this.setState({
                params: values,
                modalParams: values,
                refresh: this.state.refresh + 1
            })
        });
    };


    render() {
        const {getFieldDecorator} = this.props.form;
        const monthFormat = 'YYYY/MM';
        const dateFormat = 'YYYY/MM/DD';
        const config = {
            rules: [
                {
                    required: true,
                    message: this.common.required
                }
            ]
        };

        const token=JSON.parse(sessionStorage.getItem("token")||{}).token;
        let locale=sessionManager.get('locale');
        let exportQs=`${qs.stringify(this.state.params)}&token=${token}&locale=${locale}`;
        console.log('exportQs',exportQs);
        return (
            <div>
                <form form={this.props.form} className="SC-form">
                    <Row gutter={24} type="flex">
                        <Col xl={5} xxl={3}>
                            <FormItem
                            >
                                {getFieldDecorator('orgId')(
                                    <DepartmentPicker placeholder={'所属部门'}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col xl={4} xxl={3}>
                            <FormItem
                            >
                                {getFieldDecorator('dateType', {
                                    initialValue: this.state.params.dateType
                                })(
                                    <Select placeholder={'报表类型'} onChange={this.handleChange}>
                                        <Option value="1">年报表</Option>
                                        <Option value="2">月报表</Option>
                                        <Option value="3">日报表</Option>
                                        <Option value="4">自定义报表</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col xl={this.state.params.dateType == 4 ? 6 : 4}>
                            <FormItem
                            >
                                {this.state.params.dateType == 1 && getFieldDecorator('year', {
                                    rules: [{
                                        required: true,
                                        message: this.common.required
                                    }
                                    ],
                                    initialValue: moment().format('YYYY')
                                })(
                                    <Select placeholder={'年份'} style={{width: 150}}>
                                        {getYear().map((k, i) => {
                                            return <Option value={k} key={i}>{k}</Option>
                                        })}
                                    </Select>
                                )}
                                {this.state.params.dateType == 2 && getFieldDecorator('month', config)(
                                    <MonthPicker format={monthFormat} allowClear={false}/>
                                )}
                                {this.state.params.dateType == 3 && getFieldDecorator('day', config)(
                                    <DatePicker format={dateFormat} allowClear={false}/>
                                )}
                                {this.state.params.dateType == 4 && getFieldDecorator('selfDefining', config)(
                                    <RangePicker format={dateFormat} allowClear={false}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            <FormItem>
                                <Button type="primary" htmlType="submit"
                                        onClick={this.handleSubmit} className="ant-btn-84">{this.common.search}</Button>
                                <a href={`${axios.defaults.baseURL}/api/statistics/org/charge/export?${exportQs}`}>
                                    <Button type="primary">{this.common.exportStatement}</Button>
                                </a>
                            </FormItem>
                        </Col>
                    </Row>
                </form>
                <Grid params={this.state.params} refresh={this.state.refresh} columns={this.columns}
                      url={'api/statistics/org/chargeAnalysis/qry'}/>
            </div>
        )
    }
}

DepChargeReport = createForm()(DepChargeReport);
export default injectIntl(DepChargeReport);